﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MemoLib.Operations;

namespace MemoLib.Tasks
{
    public abstract class Task
    {
        private DateTime executeTime;
        /// <summary>
        /// 任务执行时间
        /// </summary>
        public DateTime ExecuteTime
        {
            get { return executeTime; }
            set { executeTime = value; }
        }

        /// <summary>
        /// 任务所属的工卡
        /// </summary>
        public TaskCard Card = null;

        // 任务执行完后，更新状态字段，对于循环类任务还要更新它的下次执行时间。
        public abstract void UpdateTaskStatus(ExcelOperator eop);

        /// <summary>
        /// 任务的执行
        /// </summary>
        public void Execute()
        {
            if (Card.Operations.Count > 0)
            {
                foreach (Operation op in Card.Operations)
                {
                    op.Execute();
                    ExcelOperator eop = new ExcelOperator(ConfigOperator.GetExcelPath());
                    eop.OpenConn();
                    // 更新工卡状态信息
                    UpdateTaskStatus(eop);
                    // 插入到任务列表
                    // 如果配置允许app任务插入TodoList或者不允许插入同时该任务是消息类任务，那么插入任务列表
                    if (ConfigOperator.IfInsertAppTaskToTodoListFlag() ||
                        (!ConfigOperator.IfInsertAppTaskToTodoListFlag() && this.Card.ExecuteType.ToLower() == "message"))
                    {
                        TodoTaskCard taskCard = new TodoTaskCard();
                        taskCard.Context = this.Card.Context;
                        taskCard.ID = this.Card.CardID;
                        taskCard.TaskItemType = this.TaskItemType;
                        eop.InsertToDoTask(taskCard);
                    }
                    eop.CloseConn();
                }
            }

            if (ExecuteContext.MessageBusket.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (string message in ExecuteContext.MessageBusket)
                {
                    sb.AppendLine(message);
                }
            }
        }

        public TaskType TaskItemType
        {
            get {
                return this.Card as OnceTaskCard != null ? TaskType.Once : TaskType.Cycle;
            }
        }
    }
}
